package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.admin.utils.buckettool.BaseBucketTool;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Course;
import com.iot08.common.entity.app.Knowledge;
import com.iot08.common.response.Response;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.UUIDGenerator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Description: 课程页业务
 * @author: Rock
 * @time: 2021/5/31 10:31
 */
@Service
public class CourseService extends BaseService<Course> {

    @Resource
    private UserService userService;
    @Resource
    private OperationService operationService;
    @Resource
    private BaseBucketTool baseBucketTool;

    /**
     * @param name
     * @time: 2021/5/31 10:32
     * @author: Rock
     * @version 1.0
     */
    public Course getByName(String name) {
        return this.findOne(new Query(Criteria.where("name").is(name).and("deleted").is(0)));
    }

    /**
     * @param page
     * @time: 2021/5/31 10:32
     * @author: Rock
     * @version 1.0
     */
    public Page<Course> list(PageVO page) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Sort.Order.desc("create_time")));
        pageable.setPage(page);
        Criteria criteria = Criteria.where("deleted").is(0);
        if (StringUtil.isNotBlank(page.getSearchValue())) {
            criteria.and("name").regex(".*?" + page.getSearchValue() + ".*?", "i");
        }
        Query query = new Query(criteria);
        long count = this.count(query);
        page.setTotalResult((int) count);
        List<Course> list = this.find(query.with(pageable));
        for (Course course : list) {
            course.setUser(userService.findById(course.getCreator()));
        }
        Page<Course> result = new PageImpl<Course>(list, pageable, count);
        return result;
    }


    public void add(Course course, SysUser user, String ip, MultipartFile file) throws IOException {
        if (course != null && getByName(course.getName()) == null) {
            course.setId(UUIDGenerator.generate());
            course.setDeleted(0);
            course.setCreateTime(new Date());
            course.setCreator(user.getId());
            if (file != null && !file.isEmpty()) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String includeQRcodeImage = BaseBucketTool.COURSE_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
                baseBucketTool.upload(includeQRcodeImage, file,1);
                course.setImgUrl(baseBucketTool.getDOMAIN() + includeQRcodeImage);
            }
            this.save(course);
            operationService.add(user, ip, "课程页管理", "添加",
                    String.format("添加课程页: %s ", course.getName()));
        }
    }

    /**
     * @param course
     * @param user
     * @param ip
     * @param file
     * @time: 2021/5/31 14:42
     * @author: Rock
     * @version 1.0
     */
    public void update(Course course, SysUser user, String ip, MultipartFile file) throws IOException {
        Update update = new Update();
        update.set("price", course.getPrice());
        update.set("original_price", course.getOriginalPrice());
        update.set("name", course.getName());
        update.set("index", course.getIndex());
        update.set("update_time", new Date());
        if (file != null && !file.isEmpty()) {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String includeQRcodeImage = BaseBucketTool.COURSE_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
            baseBucketTool.upload(includeQRcodeImage, file, 1);
            update.set("img_url", baseBucketTool.getDOMAIN() + includeQRcodeImage);
        }
        if (StringUtil.isNotBlank(course.getWebUrl())) {
            update.set("web_url", course.getWebUrl());
        }
        this.updateById(course.getId(), update);
        operationService.add(user, ip, "课程页管理", "编辑",
                String.format("编辑课程页: %s ", course.getName()));
    }

    /**
     * @param id
     * @param user
     * @param ip
     * @time: 2021/5/31 11:52
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> updateDel(String id, SysUser user, String ip) {
        Course course = this.findById(id);
        if (course != null) {
            Update update = new Update();
            update.set("deleted", 1);
            update.set("update_time", new Date());
            this.updateById(id, update);
            operationService.add(user, ip, "课程页管理", "删除",
                    String.format("删除课程页: %s ", course.getName()));
            return Response.successResponse();
        }
        return Response.failedResponse();
    }

}
